package cn.com.greatwall.oauth2.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.stream.Collectors;

import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import cn.com.greatwall.common.constant.SecurityConstants;
import cn.com.greatwall.common.utils.RsaUtils;

/**
 * @Author herw
 * @Time 2022-01-06 12:32:18
 * @Version 1.0
 * @Description: jwt工具类
 */
public class JwtUtils {
    private static final String PUBKEY_START = "-----BEGIN PUBLIC KEY-----";
    private static final String PUBKEY_END = "-----END PUBLIC KEY-----";
    
    public static RSAPublicKey getPubKeyObj() {
        Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
        try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
            String pubKey = br.lines().collect(Collectors.joining("\n"));
            pubKey = pubKey.substring(PUBKEY_START.length(), pubKey.indexOf(PUBKEY_END));
            return RsaUtils.getPublicKey(pubKey);
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
        return null;
    }
    
    public static Jwt encode(CharSequence content, KeyProperties keyProperties) {
        KeyPair keyPair = new KeyStoreKeyFactory(keyProperties.getKeyStore().getLocation(), keyProperties.getKeyStore().getSecret().toCharArray()).getKeyPair(keyProperties.getKeyStore().getAlias());
        PrivateKey privateKey = keyPair.getPrivate();
        Signer rsaSigner = new RsaSigner((RSAPrivateKey) privateKey);
        return JwtHelper.encode(content, rsaSigner);
    }
    
    public static String encodeStr(CharSequence content, KeyProperties keyProperties) {
        return encode(content, keyProperties).getEncoded();
    }
}
